package com.ruoyi.api.worker;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.IdCardUtils;
import com.ruoyi.system.utils.TokenUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Optional;


@RestController
@RequestMapping("/api/worker/other")
@Api(tags = "社工主页功能")
public class ApiWorkerOtherController {

    @Autowired
    private IJiajiaAppraiseService jiajiaAppraiseService;

    @Autowired
    private IJiajiaWorkerService jiajiaWorkerService;

    @Autowired
    private IJiajiaWorkerRenzhengService renzhengService;

    @Autowired
    private IJiajiaCityService cityService;

    @Autowired
    private IJiajiaOrderService orderService;

    @Autowired
    private IJiajiaUserLikeService userLikeService;

    @Autowired
    private IJiajiaZiZhiService ziZhiService;

    @Autowired
    private IJiajiaHuoDongService huoDongService;


    @Autowired
    private IJiajiaProxyApplicationService  jiajiaProxyApplicationService;
    @ApiOperation("用户评价")
    @PostMapping("/appraise")
    public AjaxResult appraise(@RequestParam Integer pageNo,
                               @RequestParam Integer pageSize) {

        JiajiaAppraise appraise = new JiajiaAppraise();
        appraise.setWid(TokenUtil.getUid());
        PageHelper.startPage(pageNo,pageSize,"addtime desc");
        List<JiajiaAppraise> appraises = jiajiaAppraiseService.selectJiajiaAppraiseList(appraise);

        return AjaxResult.success(appraises);
    }

    @ApiOperation("身份认证")
    @PostMapping("/renZheng")
    public AjaxResult renZheng(@RequestParam @ApiParam(value = "真实姓名") String name,
                               @RequestParam @ApiParam(value = "身份证号码") String code,
                               @RequestParam @ApiParam(value = "身份证人像面") String aPhoto,
                               @RequestParam @ApiParam(value = "身份证国徽面") String bPhoto,
                               @RequestParam @ApiParam(value = "社工Id")Long wId,
                               @RequestParam @ApiParam(value = "社工名称")String wName,
                               @RequestParam(required = false)@ApiParam(value = "认证Id")Long id,
                               @RequestParam @ApiParam(value = "邀请人") String phone){

        JiajiaWorker worker = jiajiaWorkerService.selectJiajiaWorkerById(TokenUtil.getUid());
        JiajiaProxyApplication jiajiaProxyApplication=new JiajiaProxyApplication();
        jiajiaProxyApplication.setPhone(phone);
        List<JiajiaProxyApplication> jiajiaProxyApplications = jiajiaProxyApplicationService.selectJiajiaProxyApplicationList(jiajiaProxyApplication);
        if(!Optional.ofNullable(jiajiaProxyApplications).isPresent() || jiajiaProxyApplications.size()==0){
            return AjaxResult.error("暂不支持该认证方式,请输入推官员手机号");
        }
        worker.setInviter(phone);
        jiajiaWorkerService.updateJiajiaWorker(worker);
        if (worker == null)return AjaxResult.notLogin();
        if (worker.getCodeAuth() == 1) return AjaxResult.error("已完成认证");
        JiajiaWorkerRenzheng jiajiaWorkerRenzheng = renzhengService.selectJiajiaWorkerRenzhengByWid(worker.getId());
        if (ObjectUtil.isNotNull(jiajiaWorkerRenzheng)){
            AjaxResult.error("已提交认证，请勿重复提交");
        }
        JiajiaWorkerRenzheng renZheng = new JiajiaWorkerRenzheng();
        if (id!=null){
            renZheng = renzhengService.selectJiajiaWorkerRenzhengById(id);
        }
        renZheng.setWid(wId);
        renZheng.setwName(wName);
        renZheng.setName(name);
        renZheng.setCode(code);
        renZheng.setCodeAPhoto(aPhoto);
        renZheng.setCodeBPhoto(bPhoto);
        if (id!=null){
            renZheng.setAuthStatus(0);
            renzhengService.updateJiajiaWorkerRenzheng(renZheng);
            IdCardUtils.PersonInfo personInfo = IdCardUtils.parseIdCard(code);
            JiajiaWorker jiajiaWorker = jiajiaWorkerService.selectJiajiaWorkerById(renZheng.getWid());
            jiajiaWorker.setAge(personInfo.getAge());
            jiajiaWorker.setSex(personInfo.getGender().equals("男")?1:2);
            jiajiaWorkerService.updateJiajiaWorker(jiajiaWorker);
        }else {
            IdCardUtils.PersonInfo personInfo = IdCardUtils.parseIdCard(code);
            JiajiaWorker jiajiaWorker = jiajiaWorkerService.selectJiajiaWorkerById(renZheng.getWid());
            jiajiaWorker.setAge(personInfo.getAge());
            jiajiaWorker.setSex(personInfo.getGender().equals("男")?1:2);
            jiajiaWorkerService.updateJiajiaWorker(jiajiaWorker);
            renzhengService.insertJiajiaWorkerRenzheng(renZheng);
        }

        return AjaxResult.success("上传成功");
    }

    @ApiOperation("获取身份认证信息")
    @PostMapping("/getRenZheng")
    public AjaxResult getRenZheng() {

        JiajiaWorker worker = jiajiaWorkerService.selectJiajiaWorkerById(TokenUtil.getUid());
        if (worker == null)return AjaxResult.notLogin();

        JiajiaWorkerRenzheng renzheng = new JiajiaWorkerRenzheng();
        renzheng.setWid(worker.getId());
        List<JiajiaWorkerRenzheng> renzhengList = renzhengService.selectJiajiaWorkerRenzhengList(renzheng);
        if (renzhengList.isEmpty()){
            return AjaxResult.success();
        }else {
            renzheng = renzhengList.get(0);
            renzheng.setInviter(worker.getInviter());
            return AjaxResult.success(renzheng);
        }
    }


    @ApiOperation("修改社工个人信息")
    @PostMapping("/updateWorker")
    public AjaxResult updateWorker(@RequestParam(required = false) @ApiParam(value = "昵称") String name,
                                   @RequestParam(required = false) @ApiParam(value = "头像") String avatar,
                                   @RequestParam(required = false) @ApiParam(value = "简介") String des,
                                   @RequestParam(required = false) @ApiParam(value = "经度") String lng,
                                   @RequestParam(required = false) @ApiParam(value = "纬度") String lat,
                                   @RequestParam(required = false) @ApiParam(value = "服务范围") Integer scope,
                                   @RequestParam(required = false) @ApiParam(value = "开始服务时间") String starTime,
                                   @RequestParam(required = false) @ApiParam(value = "结束服务时间") String endTime,
                                   @RequestParam(required = false) @ApiParam(value = "区名称") String cityName
                                   ) {
        JiajiaWorker worker = jiajiaWorkerService.selectJiajiaWorkerById(TokenUtil.getUid());
        if (worker == null)AjaxResult.notLogin();
        worker.setName(name);
        worker.setAvatar(avatar);
        worker.setDes(des);
        worker.setLng(lng);
        worker.setLat(lat);
        worker.setScope(scope);
        //worker.setStarTime(starTime);
        //worker.setEndTime(endTime);
        if(!StringUtils.isEmpty(cityName)){
            JiajiaActivateCity city = new JiajiaActivateCity();
            city.setName(cityName);
            List<JiajiaActivateCity> cityList = cityService.selectJiajiaCityList(city);
            if (!cityList.isEmpty()){
                worker.setCityId(cityList.get(0).getId().intValue());
            }
        }
        jiajiaWorkerService.updateJiajiaWorker(worker);

        return AjaxResult.success("修改完成");

    }

    @ApiOperation("查询社工个人信息")
    @PostMapping("/selectWorker")
    public AjaxResult selectWorker(String lat,String lng) {

        JiajiaWorker worker = jiajiaWorkerService.selectJiajiaWorker(TokenUtil.getUid());
        if (worker == null)return AjaxResult.notLogin();
        if (worker.getLat()==null||worker.getLng()==null){
            worker.setLng(lng);
            worker.setLat(lat);
            jiajiaWorkerService.updateJiajiaWorker(worker);
        }else {
            if (!(worker.getLat().equals(lng))||!(worker.getLng().equals(lat))){
                worker.setLng(lng);
                worker.setLat(lat);
                jiajiaWorkerService.updateJiajiaWorker(worker);
            }
        }

        //计算接单率和粉丝数量
        long count = PageHelper.count(new ISelect() {
            @Override
            public void doSelect() {
                JiajiaUserLike userLike = new JiajiaUserLike();
                userLike.setWid(worker.getId());
                userLikeService.selectJiajiaUserLikeList(userLike);
            }
        });
        worker.getParams().put("fans",count);

        float totalOrder = worker.getNum().floatValue() + worker.getUnNum().floatValue();
        worker.getParams().put("jieDanLv",(int)((worker.getNum().floatValue()/totalOrder)*100)+"%");


        //资质证件
        JiajiaZiZhi ziZhi = new JiajiaZiZhi();
        ziZhi.setWid(worker.getId());
        PageHelper.startPage(1,3,"addtime desc");
        List<JiajiaZiZhi> ziZhiList = ziZhiService.selectJiajiaZiZhiList(ziZhi);
        String urls = StringUtils.listsToSbStr(ziZhiList,"url");
        worker.getParams().put("ziZhiUrl",urls);

        //查询活动
        JiajiaHuoDong huoDong = new JiajiaHuoDong();
        huoDong.setType(1l);
        huoDong.setIsShow(1l);
        huoDong.setDel(0l);
        List<JiajiaHuoDong> huoDongList = huoDongService.selectJiajiaHuoDongList(huoDong);

        worker.getParams().put("huoDongUrl","");
        if (!huoDongList.isEmpty()){
            worker.getParams().put("huoDongUrl",huoDongList.get(0));
        }

        //获取总的得分
        JiajiaAppraise reqAppraise = new JiajiaAppraise();
        reqAppraise.setWid(worker.getId());
        Double scoreRes = jiajiaAppraiseService.selectWorkerScoreByWid(reqAppraise);
        JiajiaWorker updateWorker = new JiajiaWorker();
        updateWorker.setId(worker.getId());
        if(scoreRes == null){
            updateWorker.setScore(worker.getScore());
        }else{
            updateWorker.setScore(Convert.toBigDecimal(scoreRes, BigDecimal.ZERO).setScale(1, RoundingMode.HALF_DOWN).doubleValue());
        }

        //如果积分有变化则更新到数据库中
        if(worker.getScore() != updateWorker.getScore()){
            jiajiaWorkerService.updateJiajiaWorker(updateWorker);
        }
        worker.setScore(updateWorker.getScore());
        return AjaxResult.success(worker);
    }


    @ApiOperation("修改社工当前位置")
    @PostMapping("/updateWorkerAddress")
    public AjaxResult updateWorkerAddress(@RequestParam String lat,
                                          @RequestParam String lng,
                                          @RequestParam String cityName) {

        JiajiaWorker worker = jiajiaWorkerService.selectJiajiaWorkerById(TokenUtil.getUid());


        JiajiaOrder order = new JiajiaOrder();
        order.setWid(worker.getId());
        order.getParams().put("type","4");
        List<JiajiaOrder> orderList = orderService.selectJiajiaOrderList(order);

        if (!orderList.isEmpty()){
            order = orderList.get(0);
            worker.setCityId(order.getCityId());
            worker.setLat(order.getLat());
            worker.setLng(order.getLng());
        }else {
            JiajiaActivateCity city = new JiajiaActivateCity();
            city.setName(cityName);
            List<JiajiaActivateCity> cityList = cityService.selectJiajiaCityList(city);
            if (!cityList.isEmpty()){
                worker.setCityId(cityList.get(0).getId().intValue());
            }
            worker.setLat(lat);
            worker.setLng(lng);
        }

        if (worker.getCityId().intValue() <=0)return AjaxResult.error("获取定位信息失败，请手动修改地址！");
        jiajiaWorkerService.updateJiajiaWorker(worker);

        return AjaxResult.success();
    }

}
